package com.awspaass.user.apps.restaurant;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.actionsoft.bpms.api.OpenApiClient;
import com.actionsoft.bpms.api.common.ApiResponse;
import com.actionsoft.bpms.commons.database.ColumnMapRowMapper;
import com.actionsoft.bpms.commons.formfile.model.delegate.FormFile;
import com.actionsoft.bpms.server.UserContext;
import com.actionsoft.bpms.server.bind.annotation.Controller;
import com.actionsoft.bpms.server.bind.annotation.Mapping;
import com.actionsoft.bpms.util.DBSql;
import com.actionsoft.sdk.local.SDK;
import com.actionsoft.sdk.service.model.TaskQueryModel;
import com.actionsoft.sdk.service.response.BoolResponse;
import com.actionsoft.sdk.service.response.MapResponse;
import com.actionsoft.sdk.service.response.StringResponse;
import com.actionsoft.sdk.service.response.process.ProcessInstResponse;
import com.actionsoft.sdk.service.response.task.TaskInstsGetResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.awspaas.user.apps.shhtaerospaceindustrial.util.CoreUtil;

@Controller
public class AppCmdPeparedDish {

	@Mapping("com.awspaass.user.apps.Restaurant_getUserInfo")
	public String getUserInfo(UserContext uc) {
		JSONObject returnData = new JSONObject();
		String userName = uc.getUserName();
		String userMobile = uc.getUserModel().getMobile();
		String userDeptname = uc.getCompanyModel().getExt2();
		returnData.put("username", userName);
		returnData.put("tel", userMobile);
		returnData.put("dept", userDeptname);
		return returnData.toString();
	}

	@Mapping("com.awspaass.user.apps.Restaurant_getAllAreas")
	public String getAllAreas() {
		JSONObject result = new JSONObject();
		try {
			String querySql = "select t.cnname ,t.itemno from  BO_ACT_DICT_KV_ITEM t where t.dictkey='shdininghallarea' and itemno<30 ";
			List<Map<String, Object>> diningList = DBSql.query(querySql, new ColumnMapRowMapper(), new Object[] {});
			if (diningList == null || diningList.isEmpty()) {
				result.put("status", "1");
				result.put("message", "未查询到食堂列表信息");
				return result.toString();
			}
			JSONArray itemArray = new JSONArray();
			for (int i = 0; i < diningList.size(); i++) {
				Map<String, Object> urlMap = diningList.get(i);
				JSONObject item = new JSONObject();
				String name = CoreUtil.objToStr(urlMap.get("CNNAME"));
				String itemNo = CoreUtil.objToStr(urlMap.get("ITEMNO"));
				item.put("text", name);
				item.put("id", itemNo);
				itemArray.add(item);
			}
			result.put("status", "0");
			result.put("data", itemArray);

		} catch (Exception e) {
			e.printStackTrace();
			result.put("status", "1");
			result.put("message", e.getMessage());
		}
		return result.toString();
	}

	@Mapping("com.awspaass.user.apps.Restaurant_getAllDisheSizesByDining")
	public String getAllDisheSizesByDining(String diningId) {

		JSONObject result = new JSONObject();
		try {
			
			//航天园区|东川园区|松江园区|浦江园区|金都路园区|双创园区|所有园区
			//根据食堂所在园区和食堂id进行查询
			//航天园区：第1.2.3.4.7食堂
			//东川园区：第8.9.11食堂
			//金都路：第6食堂
			//浦江镇：第12.13.15食堂
			//松江园区：第10食堂
			//双创：第18食堂
			String appednsql="";
			if(!("").equals(diningId)&&diningId!=null) {
				if(("1").equals(diningId)||("2").equals(diningId)||("3").equals(diningId)||("4").equals(diningId)||("7").equals(diningId)) {
					 appednsql=" and (a.location='所有园区'  or a.location='航天园区'  ) " ;
				}
				else if(("8").equals(diningId)||("9").equals(diningId)||("11").equals(diningId)) {
					 appednsql=" and (a.location='所有园区'  or a.location='东川园区'  ) " ;
				}
				else if(("6").equals(diningId)) {
					 appednsql=" and (a.location='所有园区'  or a.location='金都路园区'  ) " ;
				}
				else if(("12").equals(diningId)||("13").equals(diningId)||("15").equals(diningId)) {
					 appednsql=" and (a.location='所有园区'  or a.location='金都路园区'  ) " ;
				}
				else if(("10").equals(diningId)) {
					 appednsql=" and (a.location='所有园区'  or a.location='松江园区'  ) " ;
				}
				else if(("18").equals(diningId)) {
					 appednsql=" and (a.location='所有园区'  or a.location='双创园区'  ) " ;
				}
			}

			String queryCountSql = "select count(a.caipintype)as count, a.caipintype from BO_EU_SHSYST_CAIDANHEAD a where a.isorderbylong='1'  "
				//	+ "and a.area = '"					+ diningId 	+ "' group by a.caipintype ";
					+ appednsql 	+ " group by a.caipintype ";

			// System.out.println(queryCountSql);
			List<Map<String, Object>> countList = DBSql.query(queryCountSql, new ColumnMapRowMapper(), new Object[] {});
			JSONArray itemArray = new JSONArray();
			for (int i = 0; i < countList.size(); i++) {
				JSONObject item = new JSONObject();
				Map<String, Object> countMap = countList.get(i);
				String count = CoreUtil.objToStr(countMap.get("COUNT"));
				String dishType = CoreUtil.objToStr(countMap.get("CAIPINTYPE"));
				item.put("class", dishType);
				item.put("count", count);
				itemArray.add(item);
			}
			result.put("status", "0");
			result.put("data", itemArray);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("status", "1");
			result.put("message", e.getMessage());
		}

		return result.toString();
	}

	@Mapping("com.awspaass.user.apps.Restaurant_getAllDishesByKind")
	public String getAllDinshesByKind(UserContext uc, String diningId, String foodKind) {
		JSONObject result = new JSONObject();
		try {
			
			//航天园区|东川园区|松江园区|浦江园区|金都路园区|双创园区|所有园区
			//根据食堂所在园区和食堂id进行查询
			//航天园区：第1.2.3.4.7食堂
			//东川园区：第8.9.11食堂
			//金都路：第6食堂
			//浦江镇：第12.13.15食堂
			//松江园区：第10食堂
			//双创：第18食堂
			String appednsql="";
			if(!("").equals(diningId)&&diningId!=null) {
				if(("1").equals(diningId)||("2").equals(diningId)||("3").equals(diningId)||("4").equals(diningId)||("7").equals(diningId)) {
					 appednsql=" and (a.location='所有园区'  or a.location='航天园区'  ) " ;
				}
				else if(("8").equals(diningId)||("9").equals(diningId)||("11").equals(diningId)) {
					 appednsql=" and (a.location='所有园区'  or a.location='东川园区'  ) " ;
				}
				else if(("6").equals(diningId)) {
					 appednsql=" and (a.location='所有园区'  or a.location='金都路园区'  ) " ;
				}
				else if(("12").equals(diningId)||("13").equals(diningId)||("15").equals(diningId)) {
					 appednsql=" and (a.location='所有园区'  or a.location='金都路园区'  ) " ;
				}
				else if(("10").equals(diningId)) {
					 appednsql=" and (a.location='所有园区'  or a.location='松江园区'  ) " ;
				}
				else if(("18").equals(diningId)) {
					 appednsql=" and (a.location='所有园区'  or a.location='双创园区'  ) " ;
				}
			}

			String queryCountSql = "select * from BO_EU_SHSYST_CAIDANHEAD a where a.isorderbylong='1'  and a.caipintype = '" + foodKind 
					+ "'"+appednsql;

			// System.out.println(queryCountSql);
			List<Map<String, Object>> foodList = DBSql.query(queryCountSql, new ColumnMapRowMapper(), new Object[] {});
			JSONArray itemArray = new JSONArray();
			for (int i = 0; i < foodList.size(); i++) {
				JSONObject foodObj = new JSONObject();
				Map<String, Object> foodMap = foodList.get(i);
				String dishName = CoreUtil.objToStr(foodMap.get("CAIPINNAME"));
				String dishDescribe = CoreUtil.objToStr(foodMap.get("CAIPINRESUME"));
				String dishPrice = CoreUtil.objToStr(foodMap.get("CAIPINPRICE"));
				String boId = CoreUtil.objToStr(foodMap.get("ID"));
				String meaunit = CoreUtil.objToStr(foodMap.get("MEAUNIT"));

				List<FormFile> files = SDK.getBOAPI().getFiles(boId, "CAIPINPHOTO");
				for (FormFile file : files) {
					String downloadUrl = SDK.getBOAPI().getFileDCContext(file).getDownloadURL();
					foodObj.put("url", downloadUrl);
				}
				foodObj.put("title", dishName);
				foodObj.put("meaunit", meaunit);
				foodObj.put("desc", dishDescribe);
				foodObj.put("price", dishPrice);
				foodObj.put("id", boId);
				itemArray.add(foodObj);
			}
			result.put("status", "0");
			result.put("data", itemArray);
		} catch (Exception e) {
			e.printStackTrace();
			result.put("status", "1");
			result.put("message", e.getMessage());
		}
		return result.toString();
	}

	@Mapping("com.awspaass.user.apps.Restaurant_submitDishOrder")
	public String submitDishOrder(UserContext uc, String diningId, String takeDate, String takePeriod, String totalCost,
			String note, String foodListStr) {
		
		List<Goods> foodList = JSON.parseArray(foodListStr, Goods.class);
		System.out.println("接收的结果是：" + foodListStr);
		OpenApiClient client = new OpenApiClient("https://www.sht808.com/portal/openapi", "opapiuser4326",
				"Abcd123456@#");
		JSONObject result = new JSONObject();
		//diningId  食堂AREAid
		//takeDate  取货日期
		//检查库存是否满足客户订单数量
		 StringBuffer fhstring = new StringBuffer();//返回字符串
		for (int i = 0; i < foodList.size(); i++) {
			Goods item = foodList.get(i);
			String caipinname = CoreUtil.objToStr(item.getTitle());// 产品名称
			Integer psnordernum = CoreUtil.objToInt(item.getCount());// 预订数量
			String sqlcheck ="select lastnum from VIEW_SHSY_FOODORDERCHECKLIST  where caipinname='"+
					caipinname+"' and area = '"+diningId+"' and getfoodtime ='"+takeDate+"' ";
			String lastnum = CoreUtil.objToStr(DBSql.getString(sqlcheck,"lastnum"));//剩余数量
			if("0".equals(lastnum) || "".equals(lastnum) ) {
				String sql ="select lastnum from VIEW_SHSY_FOODORDERCHECKLIST  where caipinname='"+
						caipinname+"' and area = '"+diningId+"' ";
				String totalnum = CoreUtil.objToStr(DBSql.getString(sql,"lastnum"));//剩余数量
				Integer num =Integer.valueOf(totalnum);
				if(!"".equals(totalnum) && num.compareTo(psnordernum) ==-1) {
					fhstring.append(caipinname+"剩余："+num+"；");
				}
			
			}else {
				Integer num =Integer.valueOf(lastnum==""?"0":lastnum);
				if(num.compareTo(psnordernum) ==-1) {
					fhstring.append(caipinname+"剩余："+num+"；");
				}
			}
		}
		
		if(fhstring.length() >0) {
			result.put("status", "1");
			result.put("message",fhstring.toString());
			return result.toString();
		}

		Map<String, Object> args = new HashMap<String, Object>();
		args.put("processDefId", "obj_6ffec87318914b5080d2b61eefe25a53");

		args.put("uid", uc.getUID());
		args.put("title", uc.getUserName() + " " + takeDate + " 订单");

		ProcessInstResponse r = client.exec("process.create", args, ProcessInstResponse.class);
		com.actionsoft.sdk.service.model.ProcessInstance processInst = r.getData();

		System.out.println("已经创建了一个流程 ：" + r.getData().getId());
		String bindid = processInst.getId();

		Map<String, Object> start = new HashMap<String, Object>();
		start.put("processInstId", processInst.getId());
		ApiResponse rstart = client.exec("process.start", start, ApiResponse.class);

		Map<String, Object> taskQueryArgs = new HashMap<String, Object>();
		TaskQueryModel taskQueryModel = new TaskQueryModel();
		
		taskQueryModel.setTarget(uc.getUID());// 这里要换成用户的uid
		taskQueryModel.setProcessInstId(bindid);
		taskQueryArgs.put("tqm", taskQueryModel);
		TaskInstsGetResponse taskQueryResult = client.exec("task.query", taskQueryArgs, TaskInstsGetResponse.class);

		if (!taskQueryResult.getResult().equals("ok")) {
			result.put("status", "1");
			result.put("message", "任务启动失败：" + taskQueryResult.getMsg());
			return result.toString();
		} else {
			com.actionsoft.sdk.service.model.TaskInstance taskInstance = taskQueryResult.getData().get(0);
			String taskInstanceId = taskInstance.getId();

			// Create TableHead BO_EU_SHSYST_FOODORDER_HEAD
			Map<String, Object> boFoodOrder = new HashMap<String, Object>();
			boFoodOrder.put("boName", "BO_EU_SHSYST_FOODORDER_HEAD");

			Map<String, Object> mapFoodOrder = new HashMap<String, Object>();

			mapFoodOrder.put("AREA", diningId);
			mapFoodOrder.put("GETFOODTIME", takeDate);
			mapFoodOrder.put("NOTE", note);
			mapFoodOrder.put("TOTALCOST", totalCost);
			mapFoodOrder.put("PERIOD", takePeriod);
			mapFoodOrder.put("APPLYUID", uc.getUID());
			mapFoodOrder.put("APPLYDEPTID", uc.getDepartmentModel().getName());

			boFoodOrder.put("recordData", mapFoodOrder);
			boFoodOrder.put("bindId", bindid);
			boFoodOrder.put("uid", uc.getUID());
			StringResponse rbo = client.exec("bo.create", boFoodOrder, StringResponse.class);
			System.out.println("初始化BO：" + rbo.getData());
			String BoId = rbo.getData();

			// Create TableBody BO_EU_SHSYST_FOODORDER_BODY
			for (int i = 0; i < foodList.size(); i++) {
				Map<String, Object> boFoodBody = new HashMap<String, Object>();
				boFoodBody.put("boName", "BO_EU_SHSYST_FOODORDER_BODY");

				Map<String, Object> mapFoodBody = new HashMap<String, Object>();
				Goods item = foodList.get(i);
				mapFoodBody.put("CAIPINNAME", item.getTitle());
				mapFoodBody.put("CAIPINPRICE", item.getPrice());
				mapFoodBody.put("MEAUNIT", item.getMeaunit());
				mapFoodBody.put("PSNORDERNUM", item.getCount());
				mapFoodBody.put("SUPPLYNUM", item.getCount());
				mapFoodBody.put("ORDERMONEY", item.getCost());
				// mapFoodBody.put("SUPPLYSTATUS","");
				// mapFoodBody.put("NOTE","");
				mapFoodBody.put("CAIPINID", item.getId());

				boFoodBody.put("recordData", mapFoodBody);
				boFoodBody.put("bindId", bindid);
				boFoodBody.put("uid", uc.getUID());// 系统登录账号

				StringResponse rmxbo = client.exec("bo.create", boFoodBody, StringResponse.class);
				System.out.println("初始化BO：" + rmxbo.getData());
				String MxBoId = rmxbo.getData();

			}

			Map<String, Object> taskCommentCommitArgs = new HashMap<String, Object>();
			taskCommentCommitArgs.put("taskInstId", taskInstanceId);
			taskCommentCommitArgs.put("user", uc.getUID());

			taskCommentCommitArgs.put("actionName", "提交");
			taskCommentCommitArgs.put("commentMsg", "");
			taskCommentCommitArgs.put("isIgnoreDefaultSetting", false);
			BoolResponse taskCommentCommitResult = client.exec("task.comment.commit", taskCommentCommitArgs,
					BoolResponse.class);
			if (!taskCommentCommitResult.getResult().equals("ok")) {
				result.put("status", "1");
				result.put("message", "error commit" + taskCommentCommitResult.getMsg());
			} else {

				Map<String, Object> taskCompleteArgs = new HashMap<String, Object>();
				taskCompleteArgs.put("taskInstId", taskInstanceId);
				taskCompleteArgs.put("uid", uc.getUID());
				MapResponse taskCompleteResult = client.exec("task.complete", taskCompleteArgs, MapResponse.class);
				if (!taskCompleteResult.getResult().equals("ok")) {
					result.put("status", "1");
					result.put("message", "error commit" + taskCompleteResult.getMsg());

				} else {
					result.put("status", "0");
					result.put("message", "提交成功");

				}
			}
		}

		return result.toString();
	}

	@Mapping("com.awspaass.user.apps.Restaurant_getOrderDetails")
	public String getOrderDetails(UserContext uc) {
		JSONObject result = new JSONObject();
		try {
			String queryBindIdSql = "select a.bindid from BO_EU_SHSYST_FOODORDER_HEAD a where a.ORDERSTATUS <>6 and  a.APPLYUID= '" + uc.getUID()
					+ "' order by a.createdate desc";
			List<Map<String, Object>> bindIdList = DBSql.query(queryBindIdSql, new ColumnMapRowMapper(),
					new Object[] {});
			JSONArray orderArray = new JSONArray();
			for (int i = 0; i < bindIdList.size(); i++) {
				JSONObject orderObj = new JSONObject();
				JSONArray goodArray = new JSONArray();

				String bindId = bindIdList.get(i).get("BINDID").toString();
				String queryOrderSql = "select a.* ,b.* from BO_EU_SHSYST_FOODORDER_HEAD a,BO_EU_SHSYST_FOODORDER_BODY b where a.bindid=b.bindid and a.bindid='"
						+ bindId + "' order by a.createdate desc";
				List<Map<String, Object>> orderList = DBSql.query(queryOrderSql, new ColumnMapRowMapper(),
						new Object[] {});
				String area = "";
				String createTime = "";
				String status = "";
				float totalCost = 0;
				String takeDate = "";
				String takePeriod ="";
				int itemCount = orderList.size();

				for (int j = 0; j < orderList.size(); j++) {
					JSONObject goodObj = new JSONObject();
					Map<String, Object> goodMap = orderList.get(j);
					area = CoreUtil.objToStr(goodMap.get("AREA"));
					createTime = CoreUtil.objToStr(goodMap.get("ORDERDATE"));
					status = CoreUtil.objToStr(goodMap.get("ORDERSTATUS"));
					takeDate = CoreUtil.objToStr(goodMap.get("GETFOODTIME"));
					takePeriod = CoreUtil.objToStr(goodMap.get("PERIOD"));

					String title = CoreUtil.objToStr(goodMap.get("CAIPINNAME"));
					String foodId = CoreUtil.objToStr(goodMap.get("CAIPINID"));
					String foodCount = CoreUtil.objToStr(goodMap.get("PSNORDERNUM"));
					String foodUnit = CoreUtil.objToStr(goodMap.get("MEAUNIT"));
					String foodPrice = CoreUtil.objToStr(goodMap.get("CAIPINPRICE"));
					String foodCost = CoreUtil.objToStr(goodMap.get("ORDERMONEY"));
					
					 
					
					
					totalCost += Float.parseFloat(foodCost);
					List<FormFile> files = SDK.getBOAPI().getFiles(foodId, "CAIPINPHOTO");
					for (FormFile file : files) {
						String downloadUrl = SDK.getBOAPI().getFileDCContext(file).getDownloadURL();
						goodObj.put("url", downloadUrl);
					}
					goodObj.put("title", title);
					goodObj.put("foodid", foodId);
					goodObj.put("foodcount", foodCount);
					goodObj.put("foodunit", foodUnit);
					goodObj.put("price", foodPrice);
					goodObj.put("cost", foodCost);
					
					

					goodArray.add(goodObj);
				}
				orderObj.put("orderId", bindId);
				orderObj.put("restaurant", area);
				orderObj.put("createtime", createTime);
				orderObj.put("status", status);
				orderObj.put("count", itemCount);
				orderObj.put("totalcost", totalCost);
				orderObj.put("takeDate", takeDate);
				orderObj.put("takePeriod", takePeriod);
				orderObj.put("goods", goodArray);
				orderArray.add(orderObj);
			}
			result.put("status", 0);
			result.put("list", orderArray);
		} catch (Exception e) {
			result.put("status", 0);
			result.put("message", e.getMessage());
		}
		return result.toString();
	}

	@Mapping("com.awspaass.user.apps.Restaurant_cancelDishOrder")
	public String cancelDishOrder(UserContext uc, String orderId) {
		JSONObject result = new JSONObject();
		try {
			SDK.getProcessAPI().terminateById(orderId, uc.getUID());
			String updateOrderStatusSql = "update BO_EU_SHSYST_FOODORDER_HEAD set ORDERSTATUS='6' where BINDID ='" + orderId + "'";
			DBSql.update(updateOrderStatusSql);
			
		} catch (Exception e) {

			e.printStackTrace();
			result.put("status", "1");
			result.put("message", e.getMessage());
			return result.toString();
		}
		result.put("status", "0");
		result.put("message", "取消成功");
		return result.toString();
	}
	
	
	public static class Goods {
		private String title;
		private String id;
		private int count;
		private float price;
		private float cost;
		private String meaunit;

		public String getMeaunit() {
			return meaunit;
		}

		public void setMeaunit(String meaunit) {
			this.meaunit = meaunit;
		}

		public String getTitle() {
			return title;
		}

		public void setTitle(String title) {
			this.title = title;
		}

		public String getId() {
			return id;
		}

		public void setId(String id) {
			this.id = id;
		}

		public int getCount() {
			return count;
		}

		public void setCount(int count) {
			this.count = count;
		}

		public float getPrice() {
			return price;
		}

		public void setPrice(float price) {
			this.price = price;
		}

		public float getCost() {
			return cost;
		}

		public void setCost(float cost) {
			this.cost = cost;
		}
	}
}
